use crate::types::TResult;
use image::{DynamicImage, ImageFormat};
use std::io::Cursor;

/// 将图片格式化为字节数组
pub fn format_to_bytes(img: &DynamicImage, format: ImageFormat) -> TResult<Vec<u8>> {
    let mut buffer = Vec::new();
    let mut cursor = Cursor::new(&mut buffer);
    img.write_to(&mut cursor, format)?;
    Ok(buffer)
}

/// 将图片转换为base64字符串
pub fn img_to_base64(img: &DynamicImage, format: ImageFormat) -> TResult<String> {
    let bytes = format_to_bytes(img, format)?;
    use base64::Engine;
    let base64_string = base64::engine::general_purpose::STANDARD.encode(&bytes);
    
    let mime_type = match format {
        ImageFormat::Png => "image/png",
        ImageFormat::Jpeg => "image/jpeg",
        ImageFormat::WebP => "image/webp",
        ImageFormat::Bmp => "image/bmp",
        ImageFormat::Tiff => "image/tiff",
        _ => "image/png",
    };
    
    Ok(format!("data:{};base64,{}", mime_type, base64_string))
}

/// 调整图片大小
pub fn resize_image(img: &DynamicImage, width: u32, height: u32) -> DynamicImage {
    img.resize(width, height, image::imageops::FilterType::Lanczos3)
}

/// 裁剪图片
pub fn crop_image(img: &DynamicImage, x: u32, y: u32, width: u32, height: u32) -> DynamicImage {
    img.crop_imm(x, y, width, height)
}